package com.dou.controller;

import com.dou.entity.AppCategory;
import com.dou.entity.AppInfo;
import com.dou.entity.DataDictionary;
import com.dou.entity.PageBean;
import com.dou.service.AppCategoryService;
import com.dou.service.AppInfoService;
import com.dou.service.DataDictionaryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.util.List;
import java.util.UUID;

@Controller//作用 接受客户请求 调用service方法 返回给客户
public class App_CategoryController {
    @Autowired
    private AppInfoService appInfoService;
    @Autowired
    private DataDictionaryService dataDictionaryService;
    @Autowired
    private AppCategoryService appCategoryService;
    /*
    分页查询
    * */
    @RequestMapping("select")
    public String select(@RequestParam(value = "currentPage", defaultValue = "1", required = false) int currentPage, AppInfo appInfo, Model model){
        PageBean<AppInfo> appInfoPageBean = appInfoService.selectInfo(appInfo,currentPage);
        model.addAttribute("appBean",appInfoPageBean);
        return  "DevUser/select";
    }
    /*
    动态下拉列表 APP状态 所属平台
    * */
    @RequestMapping("appWeiHu")
    public String appWeiHu(HttpSession session,String type){
        List<DataDictionary> statusList = dataDictionaryService.selectValueName("APP状态");
        List<DataDictionary> flatFormList = dataDictionaryService.selectValueName("所属平台");
        session.setAttribute("statusList",statusList);
        session.setAttribute("flatFormList",flatFormList);
        if(type.equals("queryShow")) {
            return  "DevUser/select";
        }
        return "DevUser/appinsert";
    }
    //二级分类 三级分类
    @RequestMapping("AppCategory")
    @ResponseBody
    public List<AppCategory> AppCategory(int parentId){
        return appCategoryService.getcate(parentId);
    }
    //判断APK唯一性
    @RequestMapping("selectAPKName")
    @ResponseBody
    public AppInfo selectAPKName(String APKName){
        return appInfoService.selectAPKName(APKName);
    }

    @RequestMapping("add")
    @ResponseBody
    public String insertEmployee(AppInfo appInfo,MultipartFile mufile, HttpServletRequest request) throws Exception {
        //获取项目跟路径
        String filePath = request.getServletContext().getRealPath("/");
        //获取项目名
        String projectName = request.getContextPath();
        //将项目跟路劲下的项目名称置为空，因为图片需要在项目外的webapp下面存放,sub截取下标为1的字符
        filePath=filePath.replace(projectName.substring(1),"");
        System.out.println(filePath+"******"+projectName);

        String path = request.getServletContext().getRealPath("static/images");
        File file = new File(path);
        String message="";
        //判断文件路径是否存在，不存在时创建
        if(!file.exists()){
            file.mkdirs();
        }
        //保存数据库的路径
        String sqlPath = null;
        //定义文件保存的本地路径
        String localPath="D:\\File\\";
        //定义 文件名
        String filename=null;
        //判断文件不为空
        if(!mufile.isEmpty()){
            //生成uuid作为文件名称
            String uuid = UUID.randomUUID().toString().replaceAll("-","");
            //获得文件类型（可以判断如果不是图片，禁止上传）
            String contentType=mufile.getContentType();
            //获得文件后缀名
            String suffixName=contentType.substring(contentType.indexOf("/")+1);
            //得到 文件名
            filename=uuid+"."+suffixName;
            System.out.println(filename);
            //文件保存路径
            mufile.transferTo(new File(path+filename));

            //判断是否为限制文件类型
            if (! checkFile(mufile.getOriginalFilename())) {
                //限制文件类型，请求转发到原始请求页面，并携带错误提示信息
                message=message+"*上传类型必须为jpg,png,jpeg类型*";
            }
            //获取上传文件尺寸大小
            long requestSize = mufile.getSize();
            if (requestSize > 51200) {
                message=message+"*上传大小不能超过50K*";
            }
        }
        //把图片的相对路径保存至数据库
        sqlPath = "/static/images/"+filename;
        appInfo.setLogoPicPath(sqlPath);
        int res = appInfoService.addInfo(appInfo);
        return "DevUser/appinsert";
    }

    /**     * 判断是否为允许的上传文件类型,true表示允许     */
    private boolean checkFile(String fileName) {
        //设置允许上传文件类型
        String suffixList = "jpg,png,jpeg";
        // 获取文件后缀
        String suffix = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
        //string的contains方法判断字符串中是否存在某个字符
        if (suffixList.contains(suffix.trim().toLowerCase())) {
            return true;
        }
        return false;
    }
    /**
     * 验证文件上传是否符合要求
     */
    @RequestMapping("checkUpload")
    @ResponseBody
    public String checkUpload(MultipartFile mufile, HttpServletRequest request, HttpServletResponse response){
        String message = "";
        //判断文件不为空
        if(!mufile.isEmpty()){
            //判断是否为限制文件类型
            //限制文件类型,并携带错误提示信息
            if (! checkFile(mufile.getOriginalFilename())) {
                message=message+"*上传类型必须为jpg,png,jpeg类型*";
            }
            //获取上传文件尺寸大小
            long requestSize = mufile.getSize();
            if (requestSize > 51200) {
                message=message+"*上传大小不能超过50K*";
            }
        }
        return message;
    }

}
